package com.piggy.auth.services;

import cn.dev33.satoken.stp.StpUtil;
import com.piggy.auth.bo.OAuthReq;
import com.piggy.auth.bo.OAuthRes;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.exception.base.BaseException;
import com.piggy.common.core.utils.FeignResultUtils;
import com.piggy.common.satoken.constants.SaTokenConst;
import com.piggy.common.satoken.enums.DeviceType;
import com.piggy.common.satoken.helper.LoginHelper;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.system.api.RemoteClientService;
import com.piggy.system.api.RemoteUserService;
import com.piggy.system.api.domain.SysClientDetails;
import com.piggy.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysLoginService {

    @Resource
    private RemoteUserService userService;

    @Resource
    private RemoteClientService clientService;

    public OAuthRes login(OAuthReq oauth) {

        R<SysClientDetails> clientDetailsR = clientService.getClientDetailsById(oauth.getClientId(), SecurityConstants.INNER);
        FeignResultUtils.throwIfFailed(clientDetailsR);
        SysClientDetails clientDetails = clientDetailsR.getData();

        if (!SecurityUtils.matchesPassword(oauth.getClientSecret(), clientDetails.getClientSecret())) {
            throw new BaseException("无效客户端");
        }

        R<LoginUser> userR = userService.getUserInfo(oauth.getUserName(), SecurityConstants.INNER);
        FeignResultUtils.throwIfFailed(userR);

        String passwd = SecurityUtils.encryptPassword(oauth.getPassword());
        if (passwd.equals(userR.getData().getSysUser().getPassword())) {
            throw new BaseException("密码错误");
        }

        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = userR.getData();
        loginUser.setClientDetails(clientDetails);
        loginUser.setUserName(loginUser.getSysUser().getUserName());
        loginUser.setUserId(loginUser.getSysUser().getUserId());
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.getByCode(oauth.getDeviceType()));

        return new OAuthRes()
                .setTokenType(SaTokenConst.BEARER)
                .setAccessToken(StpUtil.getTokenValue());

    }

}
